<?php
/**
 * Created by PhpStorm.
 * User: liyu
 * Date: 2018/1/23
 * Time: 下午4:55
 */

namespace app\mobile\service;


use app\model\DelayOrder;
use app\model\Partner;
use app\model\PartnerDayProfitCount;
use app\model\ReplenishmentOrder;
use think\Cache;

class UserService extends BaseService
{
    public function login($data)
    {
        $where = [
            'phone' => $data['phone']
        ];
        $ouserInfo = Partner::getOneByWhere($where);
        if (is_null($ouserInfo)) {
            set_error_exception('partner_not_exsits');
        } else {
            $ouserInfo = $ouserInfo->toArray();
        }
        $this->checkPassword($data['password'],$ouserInfo['password']);
        $this->checkStatus($ouserInfo['status']);
        $this->isAgreement($ouserInfo['id']);
        return $token = TokenService::instance()->createToken($ouserInfo);
    }

    public function getUserInfo()
    {
        $user_id = TokenService::instance()->getUserId();
        return Partner::getOneByWhere([
            'id' => $user_id
        ])->toArray();
    }

    public function getUserProfit($where)
    {
        $user_info = Partner::getOneByWhere([
            'id' => TokenService::instance()->getUserId()
        ])->toArray();
        $map = [
            'date' => ['between time',[$where['startTime'],$where['endTime']]],
            'partner_name' => $user_info['name']
        ];
        $data = PartnerDayProfitCount::getListByWhere($map)->toArray();
        $result = [
            'order_num' => 0,
            'profit' => 0,
            'delay_order' => 0,
            'delay_fine' => 0,
            'premium' => 0,
            'payroll' => 0,
        ];
        foreach ($data as $v) {
            $result['order_num'] += $v['order_num'];
            $result['profit'] += $v['profit'];
            $result['delay_order'] += $v['delay_order'];
            $result['premium'] += $v['premium'];
            $result['payroll'] += $v['payroll'];
            $result['delay_fine'] += $v['delay_fine'];
        }
        return $result;
    }

    public function getUserProfitDetail($where,$page)
    {
        $user_info = Partner::getOneByWhere([
            'id' => TokenService::instance()->getUserId()
        ])->toArray();
        $countArray = db()->query("select count(*) as 'num' from (select `date`,`order_sn`,`partner_profit` from `yh_partner_profit` WHERE `date` BETWEEN '".$where['startTime']."' and '".$where['endTime']."' and `partner_name` = '".$user_info['name']."'"." union all select `date`,`order_sn`,`partner_profit` from `yh_partner_profit_special` WHERE `date` BETWEEN '".$where['startTime']."' and '".$where['endTime']."' and `partner_name` = '".$user_info['name']."') `t1`");
        $count = $countArray[0]['num'];
        $num = config('common.page_20');
        if ($count != 0) {
            $total_page = ceil($count/$num);
            $start_positon = ($page-1)*$num;
            $delay_order = DelayOrder::getListByWhere([
                'date' => ['between time',[$where['startTime'],$where['endTime']]],
                'partner_name' => $user_info['name']
            ])->toArray();
            $delay_order_sn = [];
            foreach ($delay_order as $v) {
                $delay_order_sn[$v['order_sn']] = $v;
            }
            $sql = "select * from (select `date`,`order_sn`,`partner_profit` from `yh_partner_profit` WHERE `date` BETWEEN '".$where['startTime']."' and '".$where['endTime']."' and `partner_name` = '".$user_info['name']."'"." union all select `date`,`order_sn`,`partner_profit` from `yh_partner_profit_special` WHERE `date` BETWEEN '".$where['startTime']."' and '".$where['endTime']."' and `partner_name` = '".$user_info['name']."') `t1` order by `date` desc limit $start_positon,$num";
            $result = db()->query($sql);
            $this->filteOrder($result);
            foreach ($result as &$v) {
                if (array_key_exists($v['order_sn'],$delay_order_sn)) {
                    $v['is_delay'] = 1;
                    $v['partner_profit'] -= $delay_order_sn[$v['order_sn']]['delay_fine'];
                } else {
                    $v['is_delay'] = 0;
                }
            }
            return [
                'current_page' => (int)$page,
                'total_page' => $total_page,
                'result' => $result,
                'page_max_count' => $num
            ];
        } else {
            return [
                'current_page' => (int)$page,
                'total_page' => 0,
                'result' => [],
                'page_max_count' => $num
            ];
        }
    }

    protected function filteOrder(&$partnerProfitData)
    {
        $order_sn = array_column($partnerProfitData,'order_sn');
        $where = ['order_sn'=>['in',$order_sn]];
        $replenishmentOrder = ReplenishmentOrder::getListByWhere($where)->toArray();
        $replenishmentOrderSn = array_column($replenishmentOrder,'order_sn');
        foreach ($partnerProfitData as $k => $v) {
            if (in_array($v['order_sn'],$replenishmentOrderSn)) {
                $partnerProfitData[$k]['partner_profit'] = 6;
            }
        }
    }

    protected function checkPassword($password,$opassword)
    {
        if (md5($password) != $opassword) {
            set_error_exception('password_error');
        }
    }

    protected function checkStatus($status)
    {
        if ($status != 0) {
            set_error_exception('account_is_off');
        }
    }

    protected function isAgreement($user_id)
    {
        $row = Partner::updateOne(['is_agreement'=>1],['id'=>$user_id]);
        $this->db_error_check($row);
    }
}